package com.oocl.scan.io;

import com.oocl.scan.handler.Handler;
import com.oocl.scan.model.JavaClassElement;
import com.oocl.scan.producer.Producer;
import com.oocl.scan.store.JavaClassStore;
import com.oocl.scan.utils.PropertiesUtil;
import com.oocl.scan.utils.StringUtil;
import java.io.File;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FileScanner {

  private List<Producer> producerList;
  private static final String EXCLUDE = "exclude_folder_path";
  private static final String EXCLUDE_FOLDER;
  private static final List<String> excludeFolderList;

  static {
    EXCLUDE_FOLDER = PropertiesUtil.getPropertyByName(EXCLUDE);
    excludeFolderList = getExcludeFolderNameList();
  }

  public FileScanner(List<Producer> producerList) {
    this.producerList = producerList;
  }

  public void scan(String path) {
    File rootFile = new File(path);
    if (!rootFile.exists()) {
      System.out.println("not a path");
      return;
    }
    LinkedList<File> fileLinkedList = new LinkedList<File>();
    File[] files = rootFile.listFiles();
    scan(fileLinkedList, files);
    File tempFile;
    while (!fileLinkedList.isEmpty()) {
      tempFile = fileLinkedList.removeFirst();
      files = tempFile.listFiles();
      scan(fileLinkedList, files);
    }
  }

  private void scan(LinkedList<File> fileLinkedList, File[] files) {
    for (File file : files) {
      if (!isExclude(file.getAbsolutePath())) {
        if (file.isDirectory()) {
          fileLinkedList.add(file);
        } else {
          producerList.forEach(producer -> {
            producer.produce(file);
          });
        }
      }
    }
  }

  private boolean isExclude(String classPath) {
    if (excludeFolderList != null) {
      boolean isExclude = false;
      for (String name : excludeFolderList) {
        if (classPath.contains(name)) {
          isExclude = true;
          break;
        }
      }
      return isExclude;
    }
    return false;
  }

  private static List<String> getExcludeFolderNameList() {
    if (StringUtil.isIncludeSubStr(EXCLUDE_FOLDER, ",")) {
      return Arrays.asList(EXCLUDE_FOLDER.split(","));
    } else if (EXCLUDE_FOLDER.length() > 0) {
      return Arrays.asList(EXCLUDE_FOLDER);
    }
    return null;
  }
}
